package com.gitee.limaozhi.socket.lesson03.example3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

/**
 * 处理器上下文
 *
 * @author hzlimaozhi
 * @date 2019/08/07 15:32
 */
public class HandlerContext {

    private String name;
    private Socket socket;
    private ExecutorService executorService;

    private InputStream inputStream;
    private OutputStream outputStream;

    /** 头处理器 */
    private Handler head;
    /** 尾处理器 */
    private Handler tail;

    private StringBuilder stringBuilder = new StringBuilder();

    public HandlerContext(String name, Socket socket, ExecutorService executorService) throws IOException {
        this.name = name;
        this.socket = socket;
        this.executorService = executorService;

        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();
    }

    public String getName() {
        return name;
    }

    /** 新起线程执行任务 */
    public void execute(Runnable runnable) {
        executorService.submit(runnable);
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    /** 添加下一个处理器 */
    public HandlerContext addLast(Handler handler) {
        handler.context(this);
        if (tail == null) {
            head = handler;
            tail = handler;
        } else {
            tail.next(handler);
            tail = handler;
        }
        return this;
    }

    /** 启动上下文 */
    public void start() {
        head.start();
    }

    /** 关闭读通道 */
    public void shutdownInput() {
        try {
            socket.shutdownInput();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 关闭写通道 */
    public void shutdownOutput() {
        try {
            socket.shutdownOutput();
            if (socket.isInputShutdown()) {
                close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 关闭 */
    public synchronized void close() {
        if (socket != null) {
            try {
                socket.close();
                print(name + "：关闭");
                System.out.println(stringBuilder.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                socket = null;
            }
        }
    }

    public void print(String content) {
        stringBuilder.append(content + "\n");
//        System.out.println(content);
    }

}
